function show(d) {
    d.style.display = 'block';
}

function hide(d) {
    d.style.display = 'none';
}

function json_encode(obj) {
    return JSON.stringify(obj);
}

function json_decode(str, a) {
    return JSON.parse(str || (a ? '[]' : '{}'));
}

function url_encode(str) {
    return encodeURIComponent(str);
}

function http_build_query(data) {
    return Object.keys(data).map(function (key) {
        return url_encode(key) + '=' + url_encode(data[key]);
    }).join('&');
}

function $(id) {
    let s = id.charAt(0);
    id = id.substr(1);
    if (s === '.') {
        return document.getElementsByClassName(id);
    } else if (s === '#') {
        return document.getElementById(id);
    } else {
        return null;
    }
}

function time() {
    return (new Date()).getTime();
}

let Ajax = {
    get: function (url, data, fn) {
        let xhr = this._xhr();
        if (xhr === null) {
            return;
        }
        if (data instanceof Object) {
            data = http_build_query(data);
        }
        if (data.length) {
            url += (url.indexOf('?') >= 0 ? '&' : '?') + data;
        }
        xhr.open('GET', url, true);
        for (let key in this._request_headers) {
            xhr.setRequestHeader(key, this._request_headers[key]);
        }
        xhr.send();
        xhr.onreadystatechange = function () {
            Ajax._cb(this, fn);
        };
    },
    post: function (url, data, fn) {
        let xhr = this._xhr();
        if (xhr === null) {
            return;
        }
        if (data instanceof Object) {
            data = http_build_query(data);
        }
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        for (let key in this._request_headers) {
            xhr.setRequestHeader(key, this._request_headers[key]);
        }
        xhr.send(data);
        xhr.onreadystatechange = function () {
            Ajax._cb(this, fn);
        };
    },
    _request_headers: {
        'X-Requested-With': 'XMLHttpRequest'
    },
    _xhr: function () {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveObject) {
            return new ActiveXobject('Microsoft.XMLHTTP');
        } else {
            alert('Your browser do not support !');
            return null;
        }
    },
    _cb: function (xhr, fn) {
        if (xhr.readyState === 4 && ((xhr.status >= 200 && xhr.status < 300) || xhr.status === 304)) {
            fn(json_decode(xhr.responseText));
        }
    }
};